#!/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from django.utils import simplejson


def GetUserInfo(req):
  """Create a dictionary of values that is generally needed on every response.

  Args:
    req: the request object.
  """
  request_uri = req.uri
  user = users.get_current_user()
  if user:
    url = users.create_logout_url("/")
    url_linktext = "Logout"
    nickname = user.nickname()
    email = user.email()
  else:
    url = users.create_login_url(request_uri)
    url_linktext = Message("Sign In")
    nickname = None
    email = None
  if (req.get("html")):
    template_values = {
        'url': url,
        'url_linktext': url_linktext,
        'nickname': nickname,
        'email': email,
        'msg': req.get("msg"),
    }
  else:
    template_values = {}
  return template_values


class AppHandler(webapp.RequestHandler):
  """App Handler to handle getting user information.

  Gets user and any other info required in all requests. Overrides initialize(),
  see class RequestHandler at
  path/to/google_appengine/google/appengine/ext/webapp/__init__.py
  """

  TEMPLATES_DIR = os.path.join(os.path.dirname(__file__), '../templates')

  def __init__(self, *args, **kwargs):
    webapp.RequestHandler.__init__(self, *args, **kwargs)
    self.template_vals = None

  def initialize(self, request, response):
    """Override"""
    webapp.RequestHandler.initialize(self, request, response)
    self.template_vals = GetUserInfo(self.request)

  def template_path(self, template_file_name):
    return os.path.join(self.TEMPLATES_DIR, template_file_name)

  def app_render(self, template_file_name, values):
    """Convenience function for substituting values into a template html file.

    Args:
      template_file_name: string name of file.
      values: dict of values to substitute into template html file.
    """
    return template.render(self.template_path(template_file_name), values)

def jsonp_render(values, callback):
  """Convenience function for rendering a dictionary as JSONP.

  Args:
    values: dict of values to translate into JSONP
  """
  json = simplejson.dumps(values)
  return 'window["' + callback + '"](' + json + ');'

